package com.ccit.order.receiver;


import com.alibaba.fastjson.JSON;
import com.ccit.model.Order;
import com.ccit.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class MyAckReceiver implements ChannelAwareMessageListener {

    @Autowired
    private OrderService orderService;


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {

            //将msg转为order对象
            String msg = message.toString();
            String[] msgArray = msg.split("'");
            Order order = stringToObject(msgArray[1]);
//            System.out.println(order+"=======================");
//                areaStr = order.getArea();
            Boolean saveOrder = orderService.saveOrder(order);
//            boolean flag = orderService.save(order);
            System.out.println("插入结果为" + saveOrder);
            channel.basicAck(deliveryTag, true); //第二个参数，手动确认可以被批处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
//			channel.basicReject(deliveryTag, true);//第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝
        } catch (Exception e) {
            channel.basicReject(deliveryTag, false);
            e.printStackTrace();
        }
    }


    private Order stringToObject(String str) {
//        String jsonString = JSON.toJSONString(str);
//        System.out.println(jsonString);
        Order order = JSON.parseObject(str, Order.class);
//            order.setId(jsonObj.getString("id"));
//            order.setIsMember(jsonObj.getInteger("isMember"));
//            order.setPhone(jsonObj.getString("phone"));
//            order.setArea(jsonObj.getString("area"));
//            order.setPrice(jsonObj.getDouble("price"));
        return order;
    }
}
